import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by eahn on 02/11/13.
 */
public class FileChecker {

    protected File target;


    public FileChecker(File target) {
        this.target = target;
    }

    public List<ComparisonResult> checkAndReturnConflicteds(List<ComparisonResult> comparisonResults) throws IOException {

        List<ComparisonResult> ret = new LinkedList<ComparisonResult>();


        for (ComparisonResult comparisonResult : comparisonResults) {

            String filename = comparisonResult.getRelativeFilename();
            File file = new File(target, filename);

            if (!file.exists()) {

                // Not exists in target
                comparisonResult.setType(ComparisonResult.ResultType.NOT_EXISTS);
                ret.add(comparisonResult);

            } else if (file.isFile()) {

                // Exists, check the content of the file

                File originalFile = comparisonResult.getFile();

                Boolean compareResult = FileUtils.contentEquals(file, originalFile);

                if (!compareResult) {

                    // File content does not match
                    comparisonResult.setType(ComparisonResult.ResultType.EXISTS_BUT_DIFFERENT);
                    ret.add(comparisonResult);
                }

            }

        }

        return ret;

    }


}
